package com.buaa.rental.Service;

import com.buaa.rental.Dao.User;
import java.util.List;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

@Service
public class UserService
{

	@Autowired
	MongoTemplate mongoTemplate;

	public User register(User user) throws Exception
	{
		try
		{
			mongoTemplate.insert(user);
		} catch (Exception e)
		{
			throw new Exception("邮箱已被注册");
		}
		return user;
	}

	public User login(String email, String psw)
	{
		Query q1 = new Query(Criteria.where("email").is(email).and("psw").is(psw));
		return mongoTemplate.findOne(q1, User.class);
	}

	public User getUserById(String id)
	{
		Query q1 = new Query(Criteria.where("id").is(id));
		return mongoTemplate.findOne(q1, User.class);
	}

	public User getUserByUid(long uid)
	{
		Query q1 = new Query(Criteria.where("uid").is(uid));
		return mongoTemplate.findOne(q1, User.class);
	}

	public List<User> getUsers()
	{
		return mongoTemplate.find(new Query(), User.class);
	}

	public void updateUser(User user)
	{
		mongoTemplate.save(user);
	}

	public List<User> getAllWorker()
	{
		return mongoTemplate.find(new Query(Criteria.where("role").is("worker")), User.class);
	}

}
